// Gets the hostname; written by Rich Gallup
// SBB 2/16/99, add MPI calls
#define STREAM 1
#include <string.h>
#include <assert.h>
#include "mpi.h"
#ifdef STREAM
#include <iostream>
#include <stdlib.h>
using namespace std;
#else
#include <stdio.h>
#endif
const int MAX_NAME = 128;

void getHost(int myid, int nodes)
{

   char name[MAX_NAME];
   int  namelen;
   MPI_Get_processor_name( name, &namelen);
   assert(namelen < MAX_NAME);
   int nlen = namelen+1;

  int *rCounts = (int *) malloc(nodes *sizeof(int));
  MPI_Gather( &nlen, 1 , MPI_INT, rCounts, 1,  MPI_INT, 0 , MPI_COMM_WORLD);

  int *displ = (int *) malloc(nodes *sizeof(int));
  displ[0] = 0;
  int k;
  for (k = 1; k < nodes; k++)
    displ[k] = displ[k-1] + rCounts[k-1];

  char *AllNames = (char *) malloc(MAX_NAME*nodes *sizeof(char));
  MPI_Gatherv ( name, nlen, MPI_CHAR, AllNames, rCounts, displ,
		 MPI_CHAR, 0, MPI_COMM_WORLD);
   if (myid == 0){
     int p;
#ifdef STREAM
     cout <<"   Hostnames:: \n";
     for (p=0; p < nodes; p++)
        cout << " @ rank " << p << ": " << AllNames+displ[p] << endl;
     cout << endl;
#else
     printf("   Hostnames:: \n");
     for (p=0; p < nodes; p++)
        printf(" @ rank %d: %s\n", p,  AllNames+displ[p]);
     fprintf(stderr,"\n");
#endif
   }
  

}
